import { Component } from '@angular/core';
import { IonicPage, ToastController } from 'ionic-angular';
import ECharts from 'echarts';
import { Router } from '@angular/router';
import { HttphandleProvider } from '../../providers/httphandle/httphandle';
import { LocalstorageProvider } from '../../providers/localstorage/localstorage';
import { Tools } from '../../tools/tools';
import { NativePageTransitions } from '@ionic-native/native-page-transitions';
import { Network } from '@ionic-native/network';

/**
 * Generated class for the AttendanceCardPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
interface lineType {  // 产线数据类型
  productionLineId: string;
  productionLineName: string;
  productionLineNumber?: string;
}
// interface proType {  // 产品列表数据类型
//   id: number;
//   name: string;
//   total: number;
//   datas: Array<{
//     value: number;
//     name: string;
//   }>
// }
@IonicPage()
@Component({
  selector: 'page-product-statistics',
  templateUrl: 'product-statistics.html',
})
export class ProductStatisticsPage extends Tools{

  private selectedLine:lineType;  // 当前展示的产线信息，默认是总体
  private lines:Array<lineType>;  // 请求到的所有可选产线
  private currentDate:string;  // 查询附属条件 查询的时间 (月,日)
  private prolist:Array<any> = [];  // 请求得到的产品列表
  private temp:number = -1;  // 当前要展示的手风琴的索引值
  private showOperationRate:boolean = false;
  private errMsg:string = '';
  private topInfo:{
    count: number
    firstPassPercent:string
    operationRate: string
  } = {
    count: 0,
    firstPassPercent: '0%',
    operationRate: '0%'
  }
  private tabindex:number = 0;  // tab 切换状态切换

  constructor(
    protected route: Router,
    private http: HttphandleProvider,
    private loc: LocalstorageProvider,
    private toastCtrl: ToastController,
    protected nativePageTransitions: NativePageTransitions,
    protected network: Network
  ) {
    super(route, nativePageTransitions, network)
    if (!this.selectedLine) {
      this.selectedLine = {
        productionLineId: '',
        productionLineName: '总体'
      }
    }
    this.currentDate = this.getCurrentDate()
    if(this.getNetworkInfo){
      this.requestGetLine(() => {
        this.requestGetStatisticsInfoByDay()
      })

    } else{
      this.toastCtrl.create({
        message: '网络不可用',
        position: 'top',
        duration: 1000
      }).present();
    }

  }

  changeTimeType(typeIndex:number){
    this.tabindex = typeIndex
    if (typeIndex == 0) {
      // 选择日统计
      this.currentDate = this.getCurrentDate()
      this.requestGetStatisticsInfoByDay()
      this.showOperationRate = false  // 开工率隐藏
    } else if (typeIndex == 1) {
      // 选择月统计
      this.currentDate = this.getLastMonth()
      this.requestGetStatisticsInfoByMonth()
      this.showOperationRate = true // 开工率显示
    }
  }

  doRefresh(refresher){
    var datearr = this.currentDate.split('-');
    if (datearr.length  == 3) {
      this.requestGetStatisticsInfoByDay(refresher);
    } else if (datearr.length == 2) {
      this.requestGetStatisticsInfoByMonth(refresher);
    }
  }

  datechanged(){
    var datearr = this.currentDate.split('-');
    if (datearr.length  == 3) {
      this.requestGetStatisticsInfoByDay();
    } else if (datearr.length == 2) {
      this.requestGetStatisticsInfoByMonth();
    }
  }

  getCurrentDate(){
    var now = new Date();
    var d;
    var m:string
    var date = now.getDate()
    var month = now.getMonth() + 1
    var year = now.getFullYear()
    d = date < 10 ? '0' + date : date + ''
    m = month < 10 ? '0' + month : month + ''
    return `${year}-${m}-${d}`
  }

  getYesterday(){
    var day1 = new Date();
    day1.setTime(day1.getTime()-24*60*60*1000);
    var res = day1.getFullYear()+"-" + (day1.getMonth()+1) + "-" + day1.getDate();
    return res;
  }
  // 获取上一个月
  getLastMonth(){
    var now = new Date();
    var last =new Date( now.setMonth(now.getMonth()));
    var premonth = last.getMonth() + 1
    var month = premonth < 10 ? '0' + premonth : month
    return last.getFullYear() + "-" + month
  }

  showAccordion(index) {
    if (index == this.temp) {
      this.temp = -1
    }else {
      this.temp=index;
    }
  }

  back(){
    this.goback()
  }
  // 跳转年度页面
  goAnnual(){
    this.openPage('annualStatistics')
  }
  // 修改产线
  changeline(){
    var datelength = this.currentDate.split('-').length;
    if (datelength == 3) {
      this.requestGetStatisticsInfoByDay()
    } else if (datelength == 2) {
      this.requestGetStatisticsInfoByMonth()
    }
  }

  selectclosehandle(){
    console.log(1)
  }

  createOptions(title,arr){
    function handlelengend(name,arr){
      var res = ''
      for(var i = 0; i < arr.length; i ++) {
        if(arr[i]['name'] == name) {
          if (name.length >= 8 ) {
            name = name.slice(0,8) + '\n' + name.slice(8)
          }
          res = name + ' (' + arr[i]['value'] + ')'
        }
      }
      return res
    }

    var baseOptions = {
      title : {
          text: '',
          x:'center',
          top: '10',
          textStyle: {
            fontWeight: "normal"
          }
      },
      color:['#3557be','#3588d9','#93d9e1','#aad48b','#fee181','#e4ac49'],
      legend: {
        type: 'scroll',
        orient: 'vertical',
        right: 15,
        top: 60,
        bottom: 20,
        formatter(name){
          return handlelengend(name,arr)
        },
        data: [],
      },
      series : [{
          name:'半径模式',
          type:'pie',
          radius : [40, 80],
          center : ['28%', '45%'],
          hoverAnimation: false,
          labelLine:{
            normal: {
              length: 15,
              length2: 10
            }
          },
          label: {
            normal: {
              show: false,
              fontSize: 14,
              formatter: function(val){
                var originalName = val.name
                if (originalName.length >= 6 ) {
                  originalName = originalName.slice(0,6) + '\n' + originalName.slice(6)
                }
                return `${originalName}\n(${val.value})`
              }
            }
          },
          data:[]
      }]
    };
    baseOptions.title.text = title + '缺陷分布'
    baseOptions.series[0].data = arr;
    for (var j = 0; j < arr.length; j ++) {
      baseOptions.legend.data.push(arr[j]['name'])
    }
    return baseOptions
  }

  createPieCharts() {
    for (let i = 0, ilen = this.prolist.length; i < ilen; i++) {
      if (this.prolist[i].defectInfo.length > 0) {
        var pie = ECharts.init(document.getElementById('pie'+i) as HTMLDivElement);
        var option = this.createOptions(this.prolist[i]['productTypeName'],this.prolist[i].defectInfo)
        pie.setOption(option)
      }
    }
  }

  requestGetLine(fn,refresher?){
    this.http.get('/app/rest/v2/services/yes_ProductionStatisticsService/getProductionLinesInfo')
    .then(res => {
      if (res && res.length > 0) {
        this.lines = res
        this.lines.splice(0, 0, {
          "productionLineName": "总体",
          "productionLineId": "",
          "productionLineNumber": "总体"
        });
        fn && fn()
      } else {
        // 没有配置任何产线
        this.lines = [];
        this.errMsg = '您尚未有任何产线'
      }
      refresher && refresher.complete()
    }).catch(err => {
      refresher && refresher.complete()
      if (err.status === 401) {
        this.http.getToken((res) => {
          this.loc.set('token', res.json())
          this.requestGetLine(fn)
        })
      } else {
        this.toastCtrl.create({
          message: err.errMsg || err,
          position: 'top',
          duration: 1000
        }).present();
        console.log("服务器或网络", err)
      }
    })
  }
  // 通过天获取统计信息
  requestGetStatisticsInfoByDay(refresher?){
    if (!this.lines || this.lines.length == 0) {
      this.requestGetLine(() => {
        this.requestGetStatisticsInfoByDay()
      },refresher)
      return false
    }
    console.log('请求日数据')
    this.http.get('/app/rest/v2/services/yes_ProductionStatisticsService/getStatisticsInfoByDay',{
      productionLineId:this.selectedLine.productionLineId,
      day: this.currentDate
    }).then(res => {
      this.topInfo.count = res.count
      this.topInfo.firstPassPercent = res.firstPassPercent
      // for (var i = 0,ilen = res.productTypeInfo.length; i < ilen; i++) {
      //   if (res.productTypeInfo[i].defectInfo.length > 0) {
      //     this.prolist.push(res.productTypeInfo[i])
      //   }
      // }
      this.prolist = res.productTypeInfo
      refresher && refresher.complete()
      setTimeout(() => {
        this.createPieCharts()
      },100)
    }).catch(err => {
      if (err.status == 401) {
        this.http.getToken((res) => {
          this.loc.set('token', res.json())
          this.requestGetStatisticsInfoByDay(refresher)
        })
      } else {
        this.toastCtrl.create({
          message: err.errMsg || err,
          position: 'top',
          duration: 1000
        }).present();
        refresher && refresher.complete()
        console.log("服务器或网络", err)
      }
    })
  }

  // 通过月获取统计信息
  requestGetStatisticsInfoByMonth(refresher?){
    if (!this.lines || this.lines.length == 0) {
      this.requestGetLine(() => {
        this.requestGetStatisticsInfoByMonth()
      })
      return false
    }
    console.log('请求月数据')
    this.http.get('/app/rest/v2/services/yes_ProductionStatisticsService/getStatisticsInfoByMonth',{
      productionLineId:this.selectedLine.productionLineId,
      month: this.currentDate
    }).then(res => {
      this.topInfo.count = res.count
      this.topInfo.firstPassPercent = res.firstPassPercent
      this.topInfo.operationRate = res.operationRate
      this.prolist = res.productTypeInfo
      refresher && refresher.complete()
      setTimeout(() => {
        this.createPieCharts()
      },100)
    }).catch(err => {
      if (err.status == 401) {
        this.http.getToken((res) => {
          this.loc.set('token', res.json())
          this.requestGetStatisticsInfoByMonth(refresher)
        })
      } else {
        this.toastCtrl.create({
          message: err.errMsg || err,
          position: 'top',
          duration: 1000
        }).present();
        refresher && refresher.complete()
        console.log("服务器或网络", err)
      }
    })
  }

}
